package com.tz.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * 通过 getSessionFactory()方法，
 * 可以返回一个单例的 sessionFactory.
 */
public class HiberanteUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	//4.x的写法
	private static SessionFactory buildSessionFactory() {
		try {
			//1.
			Configuration cfg = new Configuration();
			cfg.configure();// hibernate.cfg.xml
			//2.
			ServiceRegistry sr = new StandardServiceRegistryBuilder()
					.applySettings(cfg.getProperties())//应用配置信息
					.build();

			//3.
			return cfg.buildSessionFactory(sr);
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}
